package cn.zust.itcost.controller;

import cn.zust.itcost.common.R;
import cn.zust.itcost.entity.Notice;
import cn.zust.itcost.service.NoticeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/*公告管理*/

@Slf4j
@CrossOrigin
@Transactional
@RestController
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private NoticeService noticeService;

    /**
     * 管理员发布公告
     *
     * @param notice
     * @return
     */
    @PostMapping("/release")
    public R<Object> release(@RequestBody Notice notice){
        log.info("发布1则公告");

        //当前时间
        notice.setTime(LocalDateTime.now());

        noticeService.save(notice);

        return R.ok().message("发布成功");
    }

    /**
     * 修改公告
     *
     * @param notice
     * @return
     */
    @PutMapping("/updata")
    public R<Object> updata(@RequestBody Notice notice){
        log.info(notice.toString());

        //合法判断
        Long id = notice.getId();
        if (id!=null){
            LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Notice::getId,id);
            if (queryWrapper==null){
                return R.fail().message("无此公告");
            }
        }else {
            return R.fail().message("无法匹配该公告");
        }

        //当前时间
        notice.setTime(LocalDateTime.now());

        noticeService.updateById(notice);

        return R.ok(notice);
    }

    /**
     * 分页查询全部通知
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping
    public R<List<Notice>> page(int page, int pageSize){

        //构造分页构造器对象
        Page<Notice> pageInfo = new Page<>(page, pageSize);

        //条件构造器
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();

        //添加排序条件
        queryWrapper.orderByDesc(Notice::getTime);

        //执行分页查询
        noticeService.page(pageInfo, queryWrapper);

        //获取查询结果列表
        List<Notice> records = pageInfo.getRecords();

        return R.ok(records);
    }

    /**
     * 删除公告
     *
     * @param id
     * @return
     */
    @DeleteMapping
    public R<Object> delete(@RequestParam Long id){
        log.info("id:{}",id);

        //合法性
        if (id==null){
            return R.fail().message("通知不存在");
        }

        noticeService.removeById(id);

        return R.ok().message("通知删除成功");
    }
}
